import store from '@/store.js';

// 获取无值，无发送时间高级事件项，用于新旧事件做对比
export const getNoValLinkageItem = linkageItem => {
  const item = JSON.parse(JSON.stringify(linkageItem));
  item.events.forEach(ev => {
    ev.params.forEach(param => {
      delete param.evtParameterVal;
      delete param.sendTime;
    });
  });
  return item;
};

// 清除无参数的，无跳转的高级事件项
export const clearEmptyLinkageItems = linkageDatas => {
  const _linkageDatas = linkageDatas.filter(n => {
    if (n.hasLink) {
      return true;
    }
    let hasParam = false;
    n.events.forEach(ev => {
      if (ev.params.length > 0) {
        hasParam = true;
      }
    });
    return hasParam;
  });
  return _linkageDatas;
};

// 根据表格旧的跳转设置修正高级事件联动设置
export const fixAdvLinkage = tableDataItem => {
  if (!tableDataItem) {
    return tableDataItem;
  }
  const n = tableDataItem;
  if (n.advancedLinkage && n.advancedLinkage.linkageDatas.length) {
    return n;
  }
  n.advancedLinkage = {
    linkageDatas: [],
  };
  if (n.jumpParams && n.jumpParams.jumpUrl) {
    const { jumpParams } = n;
    jumpParams._isSyncedToAdv = true;
    n.advancedLinkage.linkageDatas.push({
      conditions: [],
      hasLink: true,
      linkConf: { ...jumpParams },
      events: [],
    });
    delete n.jumpParams;
  }
  return n;
};

export const getMatchAdvEvents = events => {
  const evtKeys = [];
  events.forEach(n => {
    if (n.type === 'in' && n.key) {
      evtKeys.push(n.key);
    }
  });
  if (!evtKeys.length) {
    return [];
  }

  const matchEvents = [];
  const { linkageDatas = [] } = store.state.VisualComponentsModule.advancedLinkage;
  linkageDatas.forEach(n => {
    n.events.forEach(n1 => {
      if (evtKeys.includes(n1.evtKey)) {
        matchEvents.push({
          evtKey: n1.evtKey,
          params: n1.params,
          sendTime: n1.params?.[0]?.sendTime || -1,
          sentByWid: n.wid,
        });
      }
    });
  });
  return matchEvents;
};

export const getMatchAdvParams = matchEvents => {
  const paramsMap = {};
  matchEvents.forEach(evt => {
    for (let i = 0; i < evt.params.length; i++) {
      const n = evt.params[i];
      paramsMap[n.evtParameterKey] = { wid: evt.sentByWid, ...n };
    }
  });
  const matchParams = Object.values(paramsMap);
  return matchParams;
};

export const formatEvents = matchEvents => {
  const fEvents = matchEvents.map(n => {
    const parameters = {};
    n.params.forEach(p => {
      parameters[p.evtParameterKey] = p.evtParameterVal;
    });

    return {
      eventKey: n.evtKey,
      parameters,
      widgetInstanceId: n.sentByWid,
      sendTime: n.sendTime,
    };
  });
  return fEvents;
};
